package com.ycg.blog.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.ObjectUtil;
import com.algolia.search.SearchClient;
import com.algolia.search.SearchIndex;
import com.algolia.search.models.indexing.*;
import com.ycg.blog.common.PageView;
import com.ycg.blog.common.R;
import com.ycg.blog.pojo.Article;
import com.ycg.blog.pojo.LoginInfo;
import com.ycg.blog.pojo.vo.WebSettings;
import com.ycg.blog.utils.CacheUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * @author YCG
 * @date 2024-03-10 21:03
 * @description 登录接口
 */
@RestController
@RequestMapping()
public class CommonController {

    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private SearchClient searchClient;

    private static final LoginInfo info = new LoginInfo();

    private static final WebSettings settings = new WebSettings();

    @GetMapping("/code")
    public R<String> code() {
        // 获取验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        String base64 = captcha.getImageBase64Data();
        return R.success(base64);
    }

    @GetMapping("/setting/get")
    public R<WebSettings> getSetting() {
        return R.success(settings);
    }

    @PostMapping("/setting/post")
    public R<WebSettings> updateSetting(WebSettings newSetting) {
        settings.setTitle(newSetting.getTitle());
        settings.setSubTitle(newSetting.getSubTitle());
        settings.setUserName(newSetting.getUserName());
        settings.setMotto(newSetting.getMotto());
        return R.success(settings);
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody LoginInfo loginInfo) {
        if (ObjectUtil.isNull(loginInfo)) {
            return R.error("对象为空");
        }
        if (notAllEquals(loginInfo)) {
            return R.error("信息错误");
        }
        StpUtil.login(loginInfo.getUsername());
        String tokenValue = StpUtil.getTokenValue();
        return R.success(tokenValue);
    }

    @GetMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        StpUtil.logoutByTokenValue(token);
        return R.success("登出成功");
    }

    @PostMapping("/search")
    public R<PageView<Article>> search(String keyword,
                                       @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                                       @RequestParam(value = "hitsPerPage", required = false, defaultValue = "5") Integer hitsPerPage
    ) {
        SearchIndex<Article> index = searchClient.initIndex("article", Article.class);
        Query query = new Query(keyword).setPage(page - 1).setHitsPerPage(hitsPerPage);
        SearchResult<Article> result = index.search(query);
        PageView<Article> view = new PageView<>();
        List<Article> hits = result.getHits().stream().map(item -> {
            item.setTitle(item.getTitle().replaceAll(keyword, " <strong style=\"color: #ff2a2a;\">" + keyword + "</strong>"));
            item.setSimple(item.getSimple().replaceAll(keyword, " <strong style=\"color: #ff2a2a;\">" + keyword + "</strong>"));
            return item;
        }).toList();
        view.setPageList(hits);
        view.setTotal(result.getNbHits());
        return R.success(view);
    }

    /**
     * 用户信息不全为空
     *
     * @param loginInfo
     * @return
     */
    private boolean notAllEquals(LoginInfo loginInfo) {
        return !(Objects.equals(loginInfo.getCode(), info.getCode())
                && Objects.equals(loginInfo.getUsername(), info.getUsername())
                && Objects.equals(loginInfo.getPassword(), info.getPassword()));
    }

    @PostConstruct
    public void initUserInfo() {
        // 初始化用户信息
        info.setUsername("202126803043");
        info.setPassword("ycg666.");
        info.setCode("asdf");

        // 初始化setting
        settings.setTitle("向往每一天");
        settings.setSubTitle("吃得苦中苦, 方为人上人");
        settings.setUserName("代码与汉堡");
        settings.setMotto("努力成为架构师");
    }

    @PostConstruct
    public void clearCache() {
        cacheUtil.removeByPattern("blog:*");
    }


}
